package com.unism.util;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.unism.common.constant.BaseConstant;

/**
 * Description: String Utils
 * 
 * @author
 * @Date Feb 10, 2012
 */
public class StringUtil {

	public static Float parseFloat(double d) {
		DecimalFormat df = new DecimalFormat("#.##");
		return Float.valueOf(df.format(d));
	}

	/**
	 * Check String is equals. targetStr compare with compareStrArray, and
	 * return true if equals one or more
	 * 
	 * @param targetStr
	 *            待比较的字符串
	 * @param compareStrArray
	 *            要比较的一个或多个字符串标准
	 * @return
	 */
	public static boolean containsIgnoreCase(final String originalStr,
			final CharSequence targetStr) {

		if (null == originalStr) {
			return false;
		}

		String originalStrCaps = originalStr.toUpperCase();
		String targetStrCaps = targetStr.toString().toUpperCase();
		return originalStrCaps.contains(targetStrCaps);
	}

	/**
	 * Check if string contains ip,此方法不能完全判断ip是否合法
	 * 
	 * @return
	 */
	public static boolean containsIp(String originalStr) {

		if (StringUtil.isBlank(originalStr))
			return false;

		Matcher match = BaseConstant.PATTERN_OF_CONTAINS_IP
				.matcher(originalStr);
		return match.matches();
	}

	/**
	 * Description: Remove {_, -, @, $, #, /, &} in string and make letter after
	 * this uppercase.<br>
	 * e.g. ni_lea-der@gmail./com -> niLeaDerGmail.Com
	 * 
	 * @param @param inputString
	 * @param @param firstCharacterUppercase The first letter is need uppercase.
	 * @return String
	 * @throws
	 */
	public static String convertToCamelCaseString(String inputString,
			boolean firstCharacterUppercase) {
		if (null == inputString) {
			return null;
		}
		StringBuilder sb = new StringBuilder();

		boolean nextUpperCase = false;
		for (int i = 0; i < inputString.length(); i++) {
			char c = inputString.charAt(i);

			switch (c) {
			case '_':
			case '-':
			case '@':
			case '$':
			case '#':
			case ' ':
			case '/':
			case '&':
				if (sb.length() > 0) {
					nextUpperCase = true;
				}
				break;

			default:
				if (nextUpperCase) {
					sb.append(Character.toUpperCase(c));
					nextUpperCase = false;
				} else {
					sb.append(c);
				}
				break;
			}
		}

		if (firstCharacterUppercase) {
			sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
		} else {
			sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
		}

		return sb.toString();
	}

	/**
	 * Return Default if originalStr is empty.
	 * 
	 * @param originalStr
	 *            待确认值
	 * @param defaultStr
	 *            默认值
	 * @return 如果originalStr为空，那么就返回defaultStr
	 */
	public static String defaultIfBlank(String originalStr, String defaultStr) {
		if (StringUtil.isBlank(originalStr)) {
			return defaultStr;
		}
		Collections.emptyList();
		return originalStr;
	}

	/**
	 * Check String is equals Ignore Case. targetStr compare with
	 * compareStrArray, and return true if equals all
	 * 
	 * @param targetStr
	 *            待比较的字符串
	 * @param compareStrArray
	 *            要比较的一个或多个字符串标准
	 * @return true if targetStr same with every string in compareStrArray
	 */
	public static boolean equalsIgnoreCaseAll(String targetStr,
			String... compareStrArray) {

		if (StringUtil.isBlank(targetStr) || null == compareStrArray
				|| 0 == compareStrArray.length) {
			return false;
		}
		for (int i = 0; i < compareStrArray.length; i++) {
			if (!targetStr.equalsIgnoreCase(compareStrArray[i])) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Check String is equals. targetStr compare with compareStrArray, and
	 * return true if equals one or more
	 * 
	 * @param targetStr
	 *            待比较的字符串
	 * @param compareStrArray
	 *            要比较的一个或多个字符串标准
	 * @return true if targetStr same with string in compareStrArray one at
	 *         least
	 */
	public static boolean equalsIgnoreCaseOne(String targetStr,
			String... compareStrArray) {

		if (StringUtil.isBlank(targetStr) || null == compareStrArray
				|| 0 == compareStrArray.length) {
			return false;
		}
		for (int i = 0; i < compareStrArray.length; i++) {
			if (targetStr.equalsIgnoreCase(compareStrArray[i])) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 通过正则表达方式，找出一个字符串中所有指定的子串
	 * 
	 * @param @param originalStr 字符串
	 * @param @param regex 待查找子串的正则表达式
	 * @return List<String> 子串集合
	 * 
	 *         <pre>
	 * 	对 /1.1.1.1:sid=0x2337c7074dofj02e,37775[1](queued=0,recved=6,sent=7,sid=0x2337c7074f1102e,sdlfjle,dsfe的结果是：
	 * [sid=0x2337c7074dofj02e, , sid=0x2337c7074f1102e, ]
	 * </pre>
	 */
	public static List<String> findAllByRegex(String originalStr, String regex) {

		if (StringUtil.isBlank(originalStr) || StringUtil.isBlank(regex))
			return null;

		List<String> targetStrList = new ArrayList<String>();
		final Pattern patternOfTargetStr = Pattern.compile(regex,
				Pattern.CANON_EQ);
		final Matcher matcherOfTargetStr = patternOfTargetStr
				.matcher(originalStr);
		/** 开始解析 */
		while (matcherOfTargetStr.find()) {
			targetStrList
					.add(StringUtil.trimToEmpty(matcherOfTargetStr.group()));
		}
		return targetStrList;
	}

	/**
	 * 通过正则表达方式，找出一个字符串中第一个指定的子串
	 * 
	 * @param @param originalStr 字符串
	 * @param @param regex 待查找子串的正则表达式
	 * @return List<String> 子串集合
	 * 
	 *         <pre>
	 * 	对 /1.1.1.1:sid=0x2337c7074dofj02e,37775[1](queued=0,recved=6,sent=7,sid=0x2337c7074f1102e,sdlfjle,dsfe的结果是：
	 * sid=0x2337c7074dofj02e,
	 * </pre>
	 */
	public static String findFirstByRegex(String originalStr, String regex) {

		if (StringUtil.isBlank(originalStr) || StringUtil.isBlank(regex))
			return "";

		final Pattern patternOfTargetStr = Pattern.compile(regex,
				Pattern.CANON_EQ);
		final Matcher matcherOfTargetStr = patternOfTargetStr
				.matcher(originalStr);
		/** 开始解析 */
		if (matcherOfTargetStr.find()) {
			return StringUtil.trimToEmpty(matcherOfTargetStr.group());
		}
		return "";
	}

	/**
	 * 生成空白行.
	 * 
	 * @param lines
	 *            行数
	 */
	public static String generateLineBlank(int lines) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < lines; i++) {
			sb.append("\n");
		}

		return sb.toString();
	}

	/**
	 * make first letter lower case for str
	 * 
	 * @return Same letter, but the first letter is lower case.
	 */
	public static String makeFirstLetterLowerCase(String str) {
		String firstLetter = str.substring(0, 1);
		return firstLetter.toLowerCase() + str.substring(1, str.length());
	}

	/***
	 * check if orginalStr is null or empty. <br>
	 * If have more than one originalStr, use isBlank(String...
	 * originalStrArray)
	 * 
	 * @param originalStr
	 *            待确认值
	 * @return true or false;
	 */
	public static boolean isBlank(String originalStr) {
		if (null == originalStr || trimToEmpty(originalStr).isEmpty()) {
			return true;
		}
		return false;
	}

	/***
	 * check if orginalStr is null or empty
	 * 
	 * @param String
	 *            ... originalStrArray
	 * @return true if have one blank at least.
	 */
	public static boolean isBlank(String... originalStrArray) {

		if (null == originalStrArray || 0 == originalStrArray.length)
			return true;
		for (int i = 0; i < originalStrArray.length; i++) {
			if (isBlank(originalStrArray[i]))
				return true;
		}
		return false;
	}

	/**
	 * check the originalStr is contain the whitespace
	 * 
	 * @param originalStr
	 * @return true if contain whitespace
	 */
	public static boolean isContainWhitespace(String originalStr) {

		if (StringUtil.isBlank(originalStr)) {
			return true;
		}
		int strLen = originalStr.length();
		for (int i = 0; i < strLen; i++) {
			char ch = originalStr.charAt(i);
			if (Character.isWhitespace(ch)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Description: Replaces last substring of this string that matches the
	 * given regular expression with the given replacement.<br>
	 * Do not worry about null pointer
	 * 
	 * @param @param regex
	 * @param @param replacement
	 * @return String
	 * @throws
	 */
	public static String replace(String originalStr, String regex,
			String replacement) {
		return StringUtil.trimToEmpty(originalStr).replace(regex, replacement);
	}

	/**
	 * Description: Replaces last substring of this string that matches the
	 * given regular expression with the given replacement.<br>
	 * Do not worry about null pointer
	 * 
	 * @param @param regex
	 * @param @param replacement
	 * @return String
	 * @throws
	 */
	public static String replaceAll(String originalStr, String replacement,
			String regex) {
		if (StringUtil.isBlank(regex))
			return originalStr;
		return StringUtil.trimToEmpty(originalStr).replace(regex, replacement);
	}

	public static String replaceAll(String originalStr, String replacement,
			String... regexArray) {

		if (0 == regexArray.length)
			return originalStr;

		for (String regex : regexArray) {
			originalStr = StringUtil
					.replaceAll(originalStr, replacement, regex);
		}

		return originalStr;
	}

	/**
	 * Description: Replaces last substring of this string that matches the
	 * given regular expression with the given replacement.
	 * 
	 * @param @param regex
	 * @param @param replacement
	 * @param @return
	 * @return String
	 * @throws
	 */
	public static String replaceLast(String originalStr, String regex,
			String replacement) {

		if (StringUtil.isBlank(originalStr))
			return "";

		int index = originalStr.lastIndexOf(regex);
		if (-1 == index)
			return originalStr;

		// 先存储这个index之前的所有str
		String temp = originalStr.substring(0, index);
		String temp2 = originalStr.substring(index, originalStr.length());

		temp2 = temp2.replaceFirst(regex, replacement);

		originalStr = temp + temp2;

		return originalStr;
	}

	/**
	 * Description: Replaces all {n} placeholder use params
	 * 
	 * @param originalStr
	 *            a string such as :
	 *            "select * from table where id={0}, name={1}, gender={3}"
	 * @param replacementParams
	 *            real params: 1,,male
	 * @note n start with 0
	 */
	public static String replaceSequenced(String originalStr,
			Object... replacementParams) {

		if (StringUtil.isBlank(originalStr))
			return "";
		if (null == replacementParams || 0 == replacementParams.length)
			return originalStr;

		for (int i = 0; i < replacementParams.length; i++) {
			String elementOfParams = replacementParams[i] + "";
			if (StringUtil.trimToEmpty(elementOfParams)
					.equalsIgnoreCase("null"))
				elementOfParams = "";
			originalStr = originalStr.replace("{" + i + "}",
					StringUtil.trimToEmpty(elementOfParams));
		}

		return originalStr;
	}

	/**
	 * 设置前缀，如果这个字符串已经是这个前缀了，那么就不作任何操作。 TODO none test
	 * */
	public static String setPrefix(String originalStr, String prefix) {
		originalStr = StringUtil.trimToEmpty(originalStr);
		prefix = StringUtil.trimToEmpty(prefix);
		if (!originalStr.startsWith(prefix)) {
			originalStr = prefix + originalStr;
		}
		return originalStr;
	}

	/**
	 * 分割字符串，如果不是指定长度，抛出异常
	 * 
	 * @param originalStr
	 *            原字符串
	 * @param regex
	 *            分割符
	 * @param fixedLength
	 *            指定fixed长度
	 * @return 分割后的字符串数组
	 * @throws Exception
	 */
	public static String[] splitWithFixedLength(String originalStr,
			String regex, int fixedLength) throws Exception {

		if (StringUtil.isBlank(regex)) {
			return new String[0];
		}

		if (StringUtil.isBlank(originalStr)) {
			if (0 == fixedLength)
				return new String[0];
			throw new Exception("指定fixedLength为：" + fixedLength
					+ ", 但是originalStr为空");
		}

		String[] strArray = originalStr.split(regex);
		if (fixedLength != strArray.length) {
			throw new Exception("指定fixedLength为：" + fixedLength
					+ ", 但是originalStr为:" + originalStr);
		}
		return strArray;
	}

	/**
	 * 分割字符串，如果小于指定长度（>=leastLength ok），抛出异常
	 * 
	 * @param originalStr
	 *            原字符串
	 * @param regex
	 *            分割符
	 * @param leastLength
	 *            指定的最小least长度
	 * @return 分割后的字符串数组
	 * @throws Exception
	 */
	public static String[] splitWithLeastLength(String originalStr,
			String regex, int leastLength) throws Exception {
		if (StringUtil.isBlank(regex)) {
			return new String[0];
		}

		if (StringUtil.isBlank(originalStr)) {
			if (0 == leastLength)
				return new String[0];
			throw new Exception("指定leastLength为：" + leastLength
					+ ", 但是originalStr为空");
		}

		String[] strArray = originalStr.split(regex);
		if (leastLength > strArray.length) {
			throw new Exception("指定leastLength为：" + leastLength
					+ ", 但是originalStr为:" + originalStr);
		}
		return strArray;
	}

	/**
	 * 分割字符串，如果大于指定长度（<=leastLength ok），抛出异常
	 * 
	 * @param originalStr
	 *            原字符串
	 * @param regex
	 *            分割符
	 * @param maxLength
	 *            指定的最大max长度
	 * @return 分割后的字符串数组
	 * @throws Exception
	 */
	public static String[] splitWithMaxLength(String originalStr, String regex,
			int maxLength) throws Exception {
		if (StringUtil.isBlank(regex)) {
			return new String[0];
		}

		if (StringUtil.isBlank(originalStr)) {
			return new String[0];
		}

		String[] strArray = originalStr.split(regex);
		if (maxLength < strArray.length) {
			throw new Exception("指定maxLength为：" + maxLength
					+ ", 但是originalStr为:" + originalStr);
		}
		return strArray;
	}

	/**
	 * 判断字符串是否超过指定长度，如何超过，添加指定后缀
	 * 
	 * @param originalStr
	 *            "银时的"
	 * @param maxLength
	 *            2
	 * @param suffix
	 *            ...
	 * @return "银时..."
	 */
	public static String subStringIfTooLong(String originalStr, int maxLength,
			String suffix) {
		if (StringUtil.isBlank(originalStr))
			return "";
		if (maxLength < 0)
			maxLength = 0;
		if (originalStr.length() > maxLength)
			return originalStr.substring(0, maxLength)
					+ StringUtil.trimToEmpty(suffix);
		return originalStr;
	}

	/** 是否null */
	public static boolean isBlank(Object object) {
		return null == object;
	}

	/**
	 * toString()方法，不会返回null
	 * 
	 * @param t
	 * @return
	 */
	public static <T> String toString(T t) {
		if (isBlank(t))
			return "";
		return t.toString();
	}

	/**
	 * Returns a copy of the string, with leading and trailing whitespace
	 * omitted. Don't worry the NullPointerException. Will never return Null.
	 * 
	 * @param originalStr
	 * @return "" or String without empty str.
	 */
	public static String trimToEmpty(String originalStr) {
		if (null == originalStr || originalStr.isEmpty())
			return "";
		if (originalStr.equals(Character.toString( ( char )2 )))
			return originalStr;
		return originalStr.trim();
	}

	public static String getQueryStringValue(String qs, String key) {
		Map<String, String> map = StringUtil.parseQueryString(qs);
		return map.get(key);
	}

	/**
	 * parse query string to Parameters.
	 * 
	 * @param qs
	 *            query string.
	 * @return Parameters instance.
	 */
	public static Map<String, String> parseQueryString(String qs) {
		if (qs == null || qs.length() == 0)
			return new HashMap<String, String>();
		return parseKeyValuePair(qs, "\\&");
	}

	/**
	 * parse key-value pair.
	 * 
	 * @param str
	 *            string.
	 * @param itemSeparator
	 *            item separator.
	 * @return key-value map;
	 */
	private static Map<String, String> parseKeyValuePair(String str,
			String itemSeparator) {
		String[] tmp = str.split(itemSeparator);
		Map<String, String> map = new HashMap<String, String>(tmp.length);
		for (int i = 0; i < tmp.length; i++) {
			Matcher matcher = BaseConstant.KVP_PATTERN.matcher(tmp[i]);
			if (matcher.matches() == false)
				continue;
			map.put(matcher.group(1), matcher.group(2));
		}
		return map;
	}

	public static String removeSpaces(String value) {
		return value.replaceAll(" ", "");
	}

	public static String upperFirstCode(String val) {
		String v = val.substring(0, 1);
		return v.toUpperCase() + val.substring(1);
	}

	public static String replaceNullToSpace(String str) {
		if (str == null) {
			return "";
		} else {
			return str;
		}
	}
	
	public static String windgoal(Float f) {
		if (f.floatValue() >= 348.76 && f.floatValue() <= 11.25) {
			return "北";
		} else if (f.floatValue() >= 11.26 && f.floatValue() <= 33.75) {
			return "北东北";
		} else if (f.floatValue() >= 33.76 && f.floatValue() <= 56.25) {
			return "东北";
		} else if (f.floatValue() >= 56.26 && f.floatValue() <= 78.75) {
			return "东东北";
		} else if (f.floatValue() >= 78.76 && f.floatValue() <= 101.25) {
			return "东";
		} else if (f.floatValue() >= 101.26 && f.floatValue() <= 123.75) {
			return "东东南";
		} else if (f.floatValue() >= 123.76 && f.floatValue() <= 146.25) {
			return "东南";
		} else if (f.floatValue() >= 146.26 && f.floatValue() <= 168.75) {
			return "南东南";
		} else if (f.floatValue() >= 168.76 && f.floatValue() <= 191.25) {
			return "南";
		} else if (f.floatValue() >= 191.26 && f.floatValue() <= 213.75) {
			return "南西南";
		} else if (f.floatValue() >= 213.76 && f.floatValue() <= 236.25) {
			return "西南";
		} else if (f.floatValue() >= 236.26 && f.floatValue() <= 258.75) {
			return "西西南";
		} else if (f.floatValue() >= 258.76 && f.floatValue() <= 281.25) {
			return "西";
		} else if (f.floatValue() >= 281.76 && f.floatValue() <= 303.75) {
			return "西西北";
		} else if (f.floatValue() >= 303.76 && f.floatValue() <= 326.25) {
			return "西北";
		} else if (f.floatValue() >= 326.26 && f.floatValue() <= 348.75) {
			return "北西北";
		}
		return "无";
	}

	public static int windlevel(Float f) {
		if (f.floatValue() > 0 && f.floatValue() <= 0.2) {
			return 0;
		} else if (f.floatValue() >= 0.3 && f.floatValue() <= 1.5) {
			return 1;
		} else if (f.floatValue() >= 1.6 && f.floatValue() <= 3.3) {
			return 2;
		} else if (f.floatValue() >= 3.4 && f.floatValue() <= 5.4) {
			return 3;
		} else if (f.floatValue() >= 5.5 && f.floatValue() <= 7.9) {
			return 4;
		} else if (f.floatValue() >= 8 && f.floatValue() <= 10.7) {
			return 5;
		} else if (f.floatValue() >= 10.8 && f.floatValue() <= 13.8) {
			return 6;
		} else if (f.floatValue() >= 13.9 && f.floatValue() <= 17.1) {
			return 7;
		} else if (f.floatValue() >= 17.2 && f.floatValue() <= 20.7) {
			return 8;
		} else if (f.floatValue() >= 20.8 && f.floatValue() <= 24.4) {
			return 9;
		} else if (f.floatValue() >= 24.5 && f.floatValue() <= 28.4) {
			return 10;
		} else if (f.floatValue() >= 28.5 && f.floatValue() <= 32.6) {
			return 11;
		} else if (f.floatValue() >= 32.7 && f.floatValue() <= 36.9) {
			return 12;
		} else if (f.floatValue() >= 37 && f.floatValue() <= 41.4) {
			return 13;
		} else if (f.floatValue() >= 41.5 && f.floatValue() <= 46.1) {
			return 14;
		} else if (f.floatValue() >= 46.2 && f.floatValue() <= 50.9) {
			return 15;
		} else if (f.floatValue() >= 51 && f.floatValue() <= 56) {
			return 16;
		} else if (f.floatValue() >= 56.1 && f.floatValue() <= 61.2) {
			return 17;
		}
		return 0;
	}
	
	public static <T> String list2String(List<T> stringList){
        if (stringList==null) {
            return null;
        }
        StringBuilder result=new StringBuilder("'");
        boolean flag=false;
        for (T string : stringList) {
            if (flag) {
                result.append("','");
            }else {
                flag=true;
            }
            result.append(string);
        }
        result.append("'");
        return result.toString();
    }
	public static <T> String list2String_v2(List<T> stringList) {
		if (stringList == null || stringList.size() == 0) {
			return null;
		}
		StringBuilder result = new StringBuilder("");
		for (T string : stringList) {
			result.append("'").append(string).append("',");
		}
		return result.substring(0,result.length()-1);
	}
	/**
	 * 判断一个字符串能否转换成Integer类型
	 * @param str
	 * @return
	 */
	public static Boolean parseToInteger(String str){
		try {
			Integer.valueOf(str);
			return true;
			
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}
	public static void main(String[] args) {
		Boolean is=parseToInteger("1a");
		System.out.println(is);
	}
}
